<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
        <div class="item_center">
          <el-image style="width: 40px;height: 40px" :src="require('@/assets/website_logo.png')"></el-image>
          <span style="color: #FFFFFF;font-size: small;margin: auto 0">轻松购后台管理</span>
        </div>
        <!-- 菜单侧栏导航栏 -->
        <div style="background-color: #545C64">
          <el-menu
              background-color="#545c64"
              :default-active="tabsActive"
              text-color="#fff"
              router
              unique-opened
          >
            <menu-tree :menuList="menuList"></menu-tree>
          </el-menu>
        </div>
      </el-aside>
      <el-container>
        <el-header>
          <div class="head_class">
            <!-- 头部 -->
            <div style="display: flex;align-items: center;margin-left: 20px">
              <el-breadcrumb :separator-icon="ArrowRight">
                <el-breadcrumb-item :to="{ path: item.path }" v-for="item in crumbs" :key="item.path"><span
                    style="font-size: large">{{ item.title }}</span>
                </el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <div style="padding-top: 5px">
              <el-image :src="require('@/assets/sousuo.png')" style="width: 25px;"></el-image>
              <el-divider direction="vertical" style="height: 40px;"/>
              <el-image :src="require('@/assets/xiaoxi.png')" style="width: 25px;"></el-image>
              <el-divider direction="vertical" style="height: 40px;"/>
              <el-dropdown trigger="click">
                <el-avatar shape="square" :size="35" :src="$imgBaseUrl+store.loginUser.avatar"/>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="logOut">
                      <el-text type="danger">退出登录</el-text>
                    </el-dropdown-item>
                    <el-dropdown-item @click="gotoActive('person-basicInfo')">详细信息</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </el-header>
        <el-main>
          <!-- 内容 此处不应该是直接绑定store里面的数据，不规范-->
          <el-tabs v-model="store.tabsActive" @tab-change="gotoActive" @tab-remove="closeTabs">
            <el-tab-pane :label="item.name" :key="item.name"
                         v-for="item in store.tabsList" :name="item.path" :closable="item.isClose===1">
              <template #label>
                <div class="custom-tabs-label">
                  <span>{{ item.name }}</span>
                </div>
              </template>
            </el-tab-pane>
          </el-tabs>
          <div v-if="!commonStore.isLoading">
            <router-view></router-view>
          </div>
          <!--  加载动画-->
          <div style="width: 100%;height: 600px;display: flex; justify-content: center; align-items: center;"
               v-else>
            <div class="loading"/>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {ElMessage, ElMessageBox} from 'element-plus'
import {useMenusStore} from '@/store/permission'
import {useRouter} from "vue-router";
import {getToken} from "@/util/token/tokenUtil";
import {getMyInfo} from "@/api/home/user";
import {onMounted, ref, watchEffect} from "vue";
import {ArrowRight} from '@element-plus/icons-vue'
import {useCommonStore} from "@/store";
import MenuTree from "@/components/menu/MenuTree";
import {storeToRefs} from 'pinia'

let {menuList, tabsActive} = storeToRefs(useMenusStore())

const commonStore = useCommonStore()
const store = useMenusStore()
const router = useRouter()
let crumbs = ref([])

function logOut() {
  ElMessageBox.confirm('确认退出登录?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    /*点击的确认*/
    const b = await store.logout()
    if (b) {
      router.push('/login')
    } else {
      ElMessage({
        showClose: true,
        message: '注销失败',
        type: 'error',
      })
    }
  }).catch(() => {
    /*点击的取消*/
  })
}

function closeTabs(node) {
  //判断删除的是否是活动页，如果是则删除并跳到前一页，
  if (node === store.tabsActive) {
    //获取当前页的索引，此处无需担心是首元素，因为我的首元素“首页”是设置的不能关闭，就不会触发这个方法，如果你的全部元素都能被删除，记得处理数组下标越界的问题
    let index = store.tabsList.findIndex(item => item.path === node)
    //激活值改为当前索引的前一个
    store.setActive(store.tabsList[index - 1].path)
  }
  store.delTabs(node)
}

function gotoActive(node) {
  /*防止退出登录时清楚缓存时触发(active的值发生变动后，本方法会触发路由跳转)*/
  if (getToken("token")) {
    store.setActive(node)
    router.push(node)
  }
}

onMounted(() => {
  if (store.loginUser) {
    getMyInfo().then(res => {
      store.setLoginUser(res.data)
    })
  }
})

watchEffect(() => {
  // 监听当前的激活页，然后计算出从顶级目录到此活动页的路径，作为面包屑
  const activeId = findElementByPath(store.menuList, store.tabsActive)
  crumbs.value = findParentAndChild(store.menuList, activeId)
})

function findParentAndChild(menuList, tabsActiveId) {
  // 创建一个空数组来存储crumb路径
  const crumbs = [];

  // 定义一个辅助函数，递归地向上查找父级
  function findParent(menuItem) {
    // 将当前元素添加到crumb路径的开始位置
    crumbs.unshift({title: menuItem.name, path: menuItem.path});

    // 如果当前元素有父级，则递归查找父级
    const parentId = menuItem.parentId || menuItem.parent; // 根据实际情况，可能是parentId或parent
    if (parentId) {
      const parentItem = findMenuItemById(menuList, parentId);
      if (parentItem) {
        findParent(parentItem); // 递归调用
      }
    }
  }

  // 辅助函数，用于在菜单列表中通过ID查找元素（包括子元素）
  function findMenuItemById(list, id) {
    for (let item of list) {
      if (item.id === id) {
        return item;
      }
      if (item.children && item.children.length > 0) {
        const childItem = findMenuItemById(item.children, id);
        if (childItem) {
          return childItem;
        }
      }
    }
    return null;
  }

  // 在menuList中查找与tabsActiveId匹配的元素
  const targetItem = findMenuItemById(menuList, tabsActiveId);
  if (targetItem) {
    // 找到了匹配的元素，开始查找其所有父级
    findParent(targetItem);
  }
  // 返回crumb路径数组
  return crumbs;
}

function findElementByPath(tree, path) {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i].path === path) {
      // 找到匹配的元素，返回其id
      return tree[i].id;
    }
    // 如果没有找到，则递归搜索子元素
    if (tree[i].children && tree[i].children.length > 0) {
      const result = findElementByPath(tree[i].children, path);
      if (result) {
        // 如果在子树中找到了匹配的元素，返回其id
        return result;
      }
    }
  }
  // 如果没有找到匹配的元素，返回null或undefined
  return null;
}

onMounted(() => {
  //登录之后打开ws连接
  commonStore.connectWebSocket()
})
</script>

<style scoped>

.head_class {
  display: flex;
  justify-content: space-between;
}

/*隐藏侧边栏滚动条*/
/*.el-aside::-webkit-scrollbar {*/
/*  display: none;*/
/*}*/

.el-header {
  height: 45px;
  padding: 0;
}

.el-aside {
  background-color: #545C64;
  display: block;
}

.el-main {
  /*top: 60px;*/
  min-height: 94vh;
  padding-top: 0;
}

.icon_class {
  width: 20px;
  height: 20px;
}
</style>
